/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.context.FacesContext;
import persistance.model.AllowedRole;

/**
 *
 * @author Bobok
 */
public class AdminJSFBean {

    @EJB
    private UserDAOLocal userDAO;
    private AllowedRole newAllowedRole = new AllowedRole();
    private HtmlDataTable allowedRolesDataTable;

    public AllowedRole getNewAllowedRole() {
        return newAllowedRole;
    }

    public void setNewAllowedRole(AllowedRole newAllowedRole) {
        this.newAllowedRole = newAllowedRole;
    }

    public List<AllowedRole> getAllowedRoles() {
        return userDAO.getAllowedRoles();
    }

    public HtmlDataTable getAllowedRolesDataTable() {
        return allowedRolesDataTable;
    }

    public void setAllowedRolesDataTable(HtmlDataTable allowedRolesDataTable) {
        this.allowedRolesDataTable = allowedRolesDataTable;
    }

    /** Creates a new instance of AdminJSFBean */
    public AdminJSFBean() {
    }

    public String addNewAllowedRole() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        FacesMessage msg;
        try {
            userDAO.persist(newAllowedRole);

            msg = new FacesMessage("Role " + newAllowedRole.getRole() + " successfuly added.");
            msg.setSeverity(FacesMessage.SEVERITY_INFO);
            ctx.addMessage("commonNotice", msg);
        } catch (Exception ex) {
            msg = new FacesMessage("Cannot add new role type.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            ctx.addMessage("commonNotice", msg);
        }
        return "admin";
    }

    public String removeAllowedRole() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        FacesMessage msg;
        AllowedRole p = (AllowedRole) allowedRolesDataTable.getRowData();
        String role = p.getRole();
        if ("admin".equals(role) || "moderator".equals(role) || "editor".equals(role) || "user".equals(role)) {
            msg = new FacesMessage("Cannot remove system role.");
            msg.setSeverity(FacesMessage.SEVERITY_ERROR);
            ctx.addMessage("commonNotice", msg);
        } else {
            try {
                userDAO.remove(p);
            } catch (Exception ex) {
                msg = new FacesMessage("Cannot remove this role (" + role + "). DB Refused.");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                ctx.addMessage("commonNotice", msg);
            }
        }
        return "admin";
    }
}
